﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Practice1 : MonoBehaviour
{
    public Transform p0;
    public Transform p1;
    public Transform planeLocation;
    public float size = 5f;


    void OnDrawGizmos()
    {
        if (p0 == null) return;
        if (p1 == null) return;
        if (planeLocation == null) return;

        var cacheColor = Gizmos.color;

        var r = GetIntersectPoint(planeLocation.forward, planeLocation.position, p0.position, p1.position);

        if (r != null)
        {
            var quat = Quaternion.FromToRotation(planeLocation.forward, Vector3.forward);
            var temp = quat * r.Value;
            var sizeHalf = size * 0.5f;

            if (temp.x <= sizeHalf
                && temp.x >= -sizeHalf
                && temp.y <= sizeHalf
                && temp.y >= -sizeHalf)
            {
                Gizmos.color = Color.red;
            }

            Gizmos.DrawWireSphere(r.Value, 0.1f);
        }

        var cacheMatrix = Gizmos.matrix;
        Gizmos.matrix = Matrix4x4.TRS(planeLocation.position, planeLocation.rotation, Vector3.one);
        Gizmos.DrawWireCube(Vector3.zero, new Vector3(size, size, 0f));
        Gizmos.matrix = cacheMatrix;
        Gizmos.color = cacheColor;
    }

    Vector3? GetIntersectPoint(Vector3 planeNormal, Vector3 planePosition, Vector3 p0, Vector3 p1)
    {
        var sign1 = Mathf.Sign(Vector3.Dot(planeNormal, (planePosition - p0).normalized));
        var sign2 = Mathf.Sign(Vector3.Dot(planeNormal, (planePosition - p1).normalized));
        if (sign1 == sign2) return null;

        var a = planeNormal.x;
        var b = planeNormal.y;
        var c = planeNormal.z;
        var d = -a * planePosition.x - b * planePosition.y - c * planePosition.z;

        var i0 = a * p0.x + b * p0.y + c * p0.z;
        var i1 = a * p1.x + b * p1.y + c * p1.z;
        var final_t = -(i1 + d) / (i0 - i1);

        var finalPoint = new Vector3()
        {
            x = p0.x * final_t + p1.x * (1 - final_t),
            y = p0.y * final_t + p1.y * (1 - final_t),
            z = p0.z * final_t + p1.z * (1 - final_t),
        };

        return finalPoint;
    }
}
